package com.fuint.common.util;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * HTTP请求工具类
 * 兼容Jakarta Servlet API (Spring Boot 3.x)
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
public class HttpRequestUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);

    /**
     * 读取HttpServletRequest的body内容
     *
     * @param request HttpServletRequest对象
     * @return body内容字符串
     */
    public static String readData(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            logger.error("读取request body失败: {}", e.getMessage(), e);
        }
        return sb.toString();
    }

    /**
     * 读取HttpServletRequest的body内容（指定编码）
     *
     * @param request HttpServletRequest对象
     * @param charset 字符编码
     * @return body内容字符串
     */
    public static String readData(HttpServletRequest request, String charset) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getInputStream(), charset))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            logger.error("读取request body失败: {}", e.getMessage(), e);
        }
        return sb.toString();
    }
}
